#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <time.h>
#include <fcntl.h>

#define PAGE_SIZE (1<<12)
#define RANDMAX 100

int main(int argc, char **argv)
{
    char *start_addr = NULL;
    size_t memlen_gb = 1;
    char *addr;
    int value = 0;
    int ret = 0;
    int fd = 0;
    int i = 0;

    srand(time(NULL));
    value = (int)(rand() % RANDMAX);

    fd = open("/dev/mem", O_RDWR);
    if (fd < 0) {
        printf("open /dev/mem failed!\n");
        return 1;
    }

    for (i = 0; i < ((unsigned long)memlen_gb << 30) / PAGE_SIZE; i++) {
        if (start_addr && *(start_addr) != value) {
            printf("write and read memory failed!\n");
            return 1;
        }
        addr = mmap(start_addr + i * PAGE_SIZE, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, fd, 0);
        if (addr == MAP_FAILED) {
            printf("mmap memory failed!\n");
            return 1;
        }
        *addr = value;
        ret = munmap(start_addr, PAGE_SIZE);
        if (ret != 0) {
            printf("unmap memory failed!\n");
            return 1;
        }
        start_addr = addr;
    }

    printf("memory test success!\n");
    return 0;
}
